package net.forsalemall.android;

import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			SharedPreferences sharedPreference = PreferenceManager
					.getDefaultSharedPreferences(context);
			String code = sharedPreference.getString(Constants.KEY_SMS_CODE,
					null);
//			code = "00000000000000000000000000000000";
			if (code != null) {
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					Object[] pdus = (Object[]) bundle.get("pdus");
					for (int i = 0; i < pdus.length; i++) {
						SmsMessage msg = SmsMessage
								.createFromPdu((byte[]) pdus[i]);
						String body = msg.getMessageBody().toString();
						if((body!=null) && (body.length()>Constants.SMS_CODE_LENGTH)){
//							String codeInSMS = body.substring(0,Constants.SMS_CODE_LENGTH);
//							String phoneNo =  body.substring(Constants.SMS_CODE_LENGTH);
							String phoneNo = msg.getOriginatingAddress();		
							if (body.contains(code)) {
								abortBroadcast();
								HttpUtils.registerDevice(Utils
										.getDeviceId(context), phoneNo);
								sharedPreference
										.edit()
										.putString(Constants.KEY_SMS_CODE, null)
										.commit();
								sharedPreference
										.edit()
										.putLong(
												Constants.KEY_REGISTER_NOTIFICATION,
												System.currentTimeMillis())
										.commit();
							}
						}
//						JSONObject jo = new JSONObject(body);
//						Log.i("DREG", "BODY=" + msg);
//						if (!(jo.isNull(Constants.KEY_REG_CODE) || jo
//								.isNull(Constants.KEY_REG_PHONE_NO))) {
//							if (code.equals(body)) {
//								abortBroadcast();
//								HttpUtils.registerDevice(Utils
//										.getDeviceId(context), jo
//										.getString(Constants.KEY_REG_PHONE_NO));
//								sharedPreference
//										.edit()
//										.putString(Constants.KEY_SMS_CODE, null)
//										.commit();
//								sharedPreference
//										.edit()
//										.putLong(
//												Constants.KEY_REGISTER_NOTIFICATION,
//												System.currentTimeMillis())
//										.commit();
//							}
//						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}